package com.hjli.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hjli.common.ShareValues;
import com.hjli.model.ArticleCommentInfo;
import com.hjli.model.EmailSendInfo;
import com.hjli.model.UserInfo;
import com.hjli.service.impl.ArticleService;
import com.hjli.service.impl.CommentService;
import com.hjli.service.impl.EmailSendService;
import com.hjli.service.impl.UserService;
import com.hjli.tool.EmailTool;
import com.hjli.tool.PropertiesTool;

@Controller
@RequestMapping("api")
public class ApiController {
	@Resource
	ArticleService articleService;
	@Resource
	CommentService commentService;
	@Resource
	UserService userService;
	@Resource
	EmailSendService emailSendService;

	@RequestMapping("user/validate")
	public @ResponseBody Map<String, Object> validate(HttpServletRequest request, HttpServletResponse response) throws Exception {
//		System.out.println("发邮件功能");
		Map<String, Object> resultMap = new HashMap<String, Object>();
		/**
		 * 合理使用该api的判断依据 1.是否在文章页面 2.是否是本网站
		 */
		if (request.getHeader("Referer") == null || request.getHeader("Referer").toString().equals(".html")) {
			resultMap.put("result", "小伙子不要调皮，请不要随意使用该接口！");
			return resultMap;
		}
		
		if(request.getParameter("email")!=null||request.getParameter("email").toString()!=""){
			if(userService.findByEmail(request.getParameter("email").toString())!=null){
				UserInfo user = userService.findByEmail(request.getParameter("email").toString());
				resultMap.put("name",user.getuName());
				return resultMap;
			}
		}
		resultMap.put("name","");
		return resultMap;
	}
	
	@RequestMapping("email/send")
	public @ResponseBody Map<String, Object> emailSend(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		/**
		 * 合理使用该api的判断依据 1.是否在文章页面 2.是否是本网站
		 */
		if (request.getHeader("Referer") == null || request.getHeader("Referer").toString().equals(".html")) {
			resultMap.put("result", "小伙子不要调皮，请不要随意使用该接口！");
			return resultMap;
		}
//		System.out.println("Referer:"+request.getHeader("Referer").toString());
		HttpSession session = request.getSession();
		EmailSendInfo emailSendInfo = (EmailSendInfo)session.getAttribute("EmailInfo");
		if(emailSendInfo!=null){
			EmailTool emailTool = new EmailTool();
    		if(emailTool.sendMsg(emailSendInfo.getEmail(), emailSendInfo.getTitle(), emailSendInfo.getMsg())=="200"){
    			emailSendInfo.setState("1");
    			emailSendService.updateByPrimaryKey(emailSendInfo);
    			Map<String,Object> map = new HashMap<String,Object>();
    			map.put("state", "200");
    			map.put("msg", "已通过邮件的形式通知对方");
    			resultMap.put("result",map);
    		}else{
    			Map<String,Object> map = new HashMap<String,Object>();
    			map.put("state", "400");
    			map.put("msg", "邮件发送失败");
    			resultMap.put("result",map);
    		}
		}
		
		return resultMap;
	}
	
	@RequestMapping("article/reply")
	public @ResponseBody Map<String, Object> comment(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		HttpSession session = request.getSession();
		/**
		 * 合理使用该api的判断依据 1.是否在文章页面 2.是否是本网站
		 */
		if (request.getHeader("Referer") == null || request.getHeader("Referer").toString().equals(".html")) {
			resultMap.put("result", "小伙子不要调皮，请不要随意使用该接口！");
			return resultMap;
		}
		
		
		if (request.getParameter("aid") == null || request.getParameter("aid").toString() == "") {
			resultMap.put("result", "参数有误！");
			return resultMap;
		}
		if (request.getParameter("name") == null || request.getParameter("name").toString() == "") {
			resultMap.put("result", "昵称不能为空！");
			return resultMap;
		}
		if (request.getParameter("email") == null || request.getParameter("email").toString() == "") {
			resultMap.put("result", "邮箱不能为空！");
			return resultMap;
		}
		if (request.getParameter("content") == null || request.getParameter("content").toString() == "") {
			resultMap.put("result", "评论内容不能为空！");
			return resultMap;
		}
		String url = "javascript:void(0);";
		if (request.getParameter("url") != null && request.getParameter("url").toString() != "") {
			url = request.getParameter("url").toString();
		}
		int pid = 0;
		if (request.getParameter("pid") != null && request.getParameter("pid").toString() != "") {
			pid = Integer.parseInt(request.getParameter("pid").toString());
		}

		int aid = Integer.parseInt(request.getParameter("aid").toString());
		String name = request.getParameter("name").toString();
		String email = request.getParameter("email").toString();
		ArticleCommentInfo articleCommentInfoValidateDate = commentService.findLastComment(email);
		Date nowDate = new Date();
		Date oldDate = articleCommentInfoValidateDate.getcTime();
		long stampTime = nowDate.getTime()-oldDate.getTime();
		long day=stampTime /(24*60*60*1000);
//		System.out.println("day:"+day);
		long hour=(stampTime /(60*60*1000)-day*24);
//		System.out.println("hour:"+hour);
		long min=((stampTime /(60*1000))-day*24*60-hour*60);
//		System.out.println("min:"+min);
		long s=(stampTime /1000-day*24*60*60-hour*60*60-min*60);
//		System.out.println(""+min+"分");
		if(min<1){
			Map<String,Object> cookieMap = new HashMap<String,Object>();
			cookieMap.put("name", name);
			cookieMap.put("email", email);
			cookieMap.put("url", url);
			cookieMap.put("data", "小伙子，是不是评论得有点快了。");
			resultMap.put("result", cookieMap);
			return resultMap;
		}
//		System.out.println("s:"+s);
		ArticleCommentInfo articleCommentInfo = commentService.findByEmail(email);
//		System.out.println("toStar"+toStar(email));
//		List<String> nameList = new ArrayList<String>();
//		nameList.add("admin");
//		nameList.add("Admin");
//		nameList.add("aDmin");
//		nameList.add("adMin");
//		nameList.add("admIn");
//		nameList.add("admiN");
//		nameList.add("ADMIN");
//		nameList.add("博主");
//		nameList.add("haojieli");
//		nameList.add("root");
//		nameList.add("ROOT");
//		nameList.add("2252487366");
//		
		if (articleCommentInfo != null) {
//			if(nameList.contains(articleCommentInfo.getcName())){
//				name = "调皮用户";
//			}
			name = articleCommentInfo.getcName();
		}
		String content = request.getParameter("content").toString();
		/**
		 * 存库在通知
		 */

		// 存入数据库
		ArticleCommentInfo commentInfo = new ArticleCommentInfo();
		commentInfo.setcContent(content);
		commentInfo.setcEmail(email);
		commentInfo.setcName(name);
		commentInfo.setcTime(new Date());
		commentInfo.setcUrl(url);
		commentInfo.setcPid(pid);
		commentInfo.setcIp("-");
		commentInfo.setcMac("-");
		commentInfo.setcAid(aid);
		// 根据文章id查出文章静态地址
		String articleUrl = articleService.findUrlById(commentInfo.getcAid());
		if (commentService.insert(commentInfo) == 1) {
			ShareValues shareValue = (ShareValues) session.getAttribute("shareValue");
			if(shareValue!=null){
				List<ArticleCommentInfo> commentList = commentService.findCommentInfoByCount(10);
				List<String> commentstrList = new ArrayList<String>();
				for (ArticleCommentInfo comment : commentList) {
					commentstrList.add(comment.getcName() + "：“" + comment.getcContent() + "”");
				}
				shareValue.setCommentStrList(commentstrList);
				session.setAttribute("shareValue", shareValue);
			}
			// 邮件通知
			if (pid != 0) {
				// 根据id来查询邮箱
				ArticleCommentInfo commentInfo2 = commentService.selectByPrimaryKey(pid);
				Properties property = PropertiesTool.getProperty("web.properties");
				String domainName = property.getProperty("webdomain").toString();
				String urlPath ="http://www.hjieli.com";
				if(request.getLocalPort()==80){
					urlPath = domainName+ request.getContextPath() + "/" + articleUrl;
				}else{
					urlPath = domainName+ ":" + request.getLocalPort()
					+ request.getContextPath() + "/" + articleUrl;
				}
				EmailSendInfo emailSendInfo = new EmailSendInfo();
				emailSendInfo.setEmail(commentInfo2.getcEmail());
				emailSendInfo.setMsg(name + " 回复“" + commentInfo.getcContent() + "”。 点击查看 " + urlPath);
				emailSendInfo.setTitle("博客回复通知 | 有用户回复了你的评论了，速速查看吧！");
				emailSendInfo.setState("0");
				emailSendService.insert(emailSendInfo);
				session.setAttribute("EmailInfo", emailSendInfo);
			} else {
				EmailSendInfo emailSendInfo = new EmailSendInfo();
				emailSendInfo.setEmail(email);
				emailSendInfo.setMsg("感谢你的支持，我查看邮箱后回复会您，请耐心等待！");
				emailSendInfo.setTitle("博客自动回复 | 感谢你的评论！");
				emailSendInfo.setState("0");
				emailSendService.insert(emailSendInfo);
				session.setAttribute("EmailInfo", emailSendInfo);
				
			}
			Map<String,Object> cookieMap = new HashMap<String,Object>();
			cookieMap.put("name", name);
			cookieMap.put("email", email);
			cookieMap.put("url", url);
			cookieMap.put("data", "success");
			resultMap.put("result", cookieMap);
		} else {
			Map<String,Object> cookieMap = new HashMap<String,Object>();
			cookieMap.put("name", name);
			cookieMap.put("email", email);
			cookieMap.put("url", url);
			cookieMap.put("data", "参数错误");
			resultMap.put("result", cookieMap);
		}
		session.setAttribute("sendTime", System.currentTimeMillis());
		return resultMap;
	}
	
	/**
	 * 回复展开（待修复）
	 */
	int node = 0;

	@RequestMapping("article/openReplys")
	public @ResponseBody Map<String, Object> replys(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (request.getHeader("Referer") == null || request.getHeader("Referer").toString().equals(".html")) {
			resultMap.put("result", "小伙子不要调皮，请不要随意使用该接口！");
			return resultMap;
		}
		if (request.getParameter("pid").toString() == "" || request.getParameter("pid") == null) {
			resultMap.put("result", "参数错误.");
			return resultMap;
		}
		int pid = Integer.parseInt(request.getParameter("pid").toString());
		String replyHtml = getHtml(pid);
		node = 0;
		resultMap.put("result", replyHtml);
		return resultMap;
	}

	/**
	 * 得到评论内容
	 * 
	 * @param pid
	 * @return
	 */
	public String getHtml(int pid) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		// System.out.println("开始" + node);
		String html = "";
		List<ArticleCommentInfo> commentList = commentService.findCommentByPid(pid);
		if (commentList != null && commentList.size() > 0) {
			node += 1;
//			System.out.println("--" + node);
			for (ArticleCommentInfo comment : commentList) {
				if (node == 1) {
					html += "<div style=\"padding-top: 15px;\">";
					if (comment.getcName().equals("博主")) {
						html += "<span style=\"color:red;\">" + comment.getcName() + "</span>：";
					} else {
						html += "<span style=\"color:#3c8dbc;\">" + comment.getcName()  + "("+toStar(comment.getcEmail())+")</span>：";
					}
					html += comment.getcContent() + "&nbsp;&nbsp;&nbsp;&nbsp;" + sdf.format(comment.getcTime())
							+ "&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"pull-right\" style=\"padding-top:4px; padding-right:15px;\"><a href=\"javascript:void(0);\" class=\"replys\" data-id=\""
							+ comment.getId()
							+ "\"> <i class=\"fa fa-reply\"></i></a></span>	<div class=\"clearfix\"></div></div>";
				} else if (node >= 2) {
					ArticleCommentInfo commentInfo = commentService.selectByPrimaryKey(comment.getcPid());
					if (commentInfo != null) {
						html += "<div style=\"padding-top: 15px;\">";
						if (comment.getcName().equals("博主")) {
							html += "<span style=\"color:red;\">" + comment.getcName() + "</span>";
						} else {
							html += "<span style=\"color:#3c8dbc;\">" + comment.getcName() + "("+toStar(comment.getcEmail())+")</span>";
						}
						html += "&nbsp;回复&nbsp;";

						if (commentInfo.getcName().equals("博主")) {
							html += "<span style=\"color:red;\">" + commentInfo.getcName() + "</span>： ";
						} else {
							html += "<span style=\"color:#3c8dbc\">" + commentInfo.getcName() + "("+toStar(comment.getcEmail())+")</span>： ";
						}
						html += comment.getcContent() + "&nbsp;&nbsp;&nbsp;&nbsp;" + sdf.format(comment.getcTime())
								+ "&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"pull-right\" style=\"padding-top:4px; padding-right:15px;\"><a href=\"javascript:void(0);\" class=\"replys\" data-id=\""
								+ comment.getId()
								+ "\"><i class=\"fa fa-reply\"></i></a></span>	<div class=\"clearfix\"></div></div>";
					}
				}

				html += getHtml(comment.getId());
			}
			node--;
		}
		return html;
	}

	public String toStar(String email){
		String dealStr = email.split("@")[0].toString();
		String suffix = "@"+email.split("@")[1].toString();
		if(dealStr.length()<=3){
			dealStr = dealStr.substring(0, dealStr.length()-1)+"***"+suffix;
		}else{
			dealStr = dealStr.substring(0, 3)+"***"+suffix;
		}
		return dealStr;
	}
}
